const webpack = require("webpack");
const minimist = require("minimist");
const argv = minimist(process.argv);

const { prod, test, api = "", debug = false } = argv;

let mode = "dev";
if (prod) {
  mode = "prod";
}
if (test) {
  mode = "test";
}

console.log(`process.env: --mode=${mode} --api=${api}`);

const defaultApiMap = {
  dev: "http://127.0.0.1:7001",
  test: "http://192.168.20.35:8399",
  prod: "https://api.codequan.com",
};

const modeOptions = {
  BUILD_ENV: mode,
  PLARFORM: "ADMIN",
  API_ORIGIN: api || defaultApiMap[mode],
  ENCODE_KEY: "admalltect202106",
  ENCODE_IV: "admalltect202106",
  MAIN_TOKEN: "CDQTKA",
};

// WebpackDefinePlugin 接收的属性值要求
for (const k in modeOptions) {
  modeOptions[k] = JSON.stringify(modeOptions[k]);
}

console.log("modeOptions:");
console.log(modeOptions);

module.exports = {
  devServer: {
    disableHostCheck: true,
    port: "8207",
  },
  css: {
    loaderOptions: {
      scss: {
        prependData: `@import "~@/main.scss";`,
      },
      sass: {
        prependData: `@import "~@/main.sass"`,
      },
    },
  },
  configureWebpack: {
    optimization: {
      splitChunks: {
        cacheGroups: {
          oss: {
            name: "chunk-oss.js",
            test: /[\\/]ali-oss[\\/]/,
            priority: 10,
            chunks: "all",
          },
          bn: {
            name: "chunk-bn.js",
            test: /[\\/]bn\.js[\\/]/,
            priority: 0,
            chunks: "all",
          },
          element: {
            name: "chunk-element-ui",
            test: /[\\/]element-ui[\\/]/,
            priority: 0,
            chunks: "all",
          },
        },
      },
    },
    plugins: [new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)],
  },
  chainWebpack: (config) => {
    // 发行或运行时启用了压缩时会生效
    if (!debug) {
      config.optimization.minimizer("terser").tap((args) => {
        args[0].terserOptions.compress.drop_console = true;
        return args;
      });
    }

    config.plugin("define").tap((args) => {
      // 强制给VUE添加环境变量,用于不同的打包环境
      args[0]["process.env"] = {
        ...args[0]["process.env"],
        ...modeOptions,
      };
      return args;
    });
  },
};
